package org.realogic.cfm.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public final class UtilImage {
	
	public static void resize(String srcImageFilename, String destImageFilename, int maxWidth, int maxHeight) throws IOException {
		if ((maxWidth < 1) || (maxHeight < 1)) {
			throw new IllegalArgumentException("maxWidth = " + maxWidth + ", maxHeight = " + maxHeight);
		}

		File inputFile = new File(srcImageFilename);
		if ((!inputFile.exists()) || (!inputFile.isFile())) {
			throw new IllegalArgumentException("无效的文件：" + srcImageFilename);
		}

		BufferedImage input = ImageIO.read(inputFile);
		int oWidth = input.getWidth();
		int oHeight = input.getHeight();

		double oWHRatio = oWidth / oHeight;
		double destWHRatio = maxWidth / maxHeight;

		int width = 0;
		int height = 0;

		if (oWHRatio >= destWHRatio) {
			if (oWidth > maxWidth) {
				width = maxWidth;
				height = (int) (maxWidth / oWHRatio);
			} else {
				width = oWidth;
				height = oHeight;
			}
		} else if (oHeight > maxHeight) {
			width = (int) (oWHRatio * maxHeight);
			height = maxHeight;
		} else {
			width = oWidth;
			height = oHeight;
		}

		BufferedImage output = new BufferedImage(width, height, 1);
		Graphics2D g2d = output.createGraphics();
		g2d.setBackground(Color.WHITE);
		g2d.fillRect(0, 0, width, height);
		int dx = oWidth < width ? (width - oWidth) / 2 : 0;
		int dy = oHeight < height ? (height - oHeight) / 2 : 0;
		int dw = Math.min(oWidth, width);
		int dh = Math.min(oHeight, height);
		g2d.drawImage(input, dx, dy, dw, dh, null);
		File outputFile = new File(destImageFilename);
		ImageIO.write(output, "jpg", outputFile);
	}
}
